package server.session;

import com.alibaba.fastjson.JSONObject;
import common.EnvelopeMessage;

import java.util.Map;

public class SessionChecker {
    public static final long TIME_OUT = 30 * 1000;

    public static void start() {
        Thread monitorThread = new Thread(() -> {
            while (true) {
                long now = System.currentTimeMillis();
                for (Map.Entry<Integer, Session> entry : SessionManager.getAll().entrySet()) {
                    Session session = entry.getValue();
                    if (now - session.getLastActiveTime() > TIME_OUT) {
                        System.out.println("用户 " + session.getClientId() + " 超时未响应，已踢下线");
                        EnvelopeMessage msg = new EnvelopeMessage("system", "kickOut", null);
                        String json = JSONObject.toJSONString(msg);
                        session.send(json);
                        session.close();
                        SessionManager.remove(session.getClientId());
                    }
                }
                try {
                    Thread.sleep(10000); // 每10秒检查一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        monitorThread.setDaemon(true);
        monitorThread.start();
    }

}
